const { Sequelize, DataTypes } = require("sequelize");

// 从环境变量中读取数据库配置
let { MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_ADDRESS = "" } = process.env;

const [host, port] = MYSQL_ADDRESS.split(":");


MYSQL_USERNAME = MYSQL_USERNAME || 'root';
MYSQL_PASSWORD = MYSQL_PASSWORD || '123456';

console.log(MYSQL_USERNAME, MYSQL_PASSWORD);

const sequelize = new Sequelize("nodejs_demo", MYSQL_USERNAME, MYSQL_PASSWORD, {
  host,
  port,
  dialect: "mysql" /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,
});

// 定义数据模型
const Counter = sequelize.define("Counter", {
  count: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 1,
  },
});

// 订单表
const Order = sequelize.define('my_pay_order', {
  id: {
    autoIncrement: true,
    type: DataTypes.INTEGER.UNSIGNED,
    allowNull: false,
    primaryKey: true,
    comment: "主键"
  },
  mch_id: {
    type: DataTypes.STRING(64),
    allowNull: false,
    comment: "商户id"
  },
  order_no: {
    type: DataTypes.STRING(64),
    allowNull: false,
    comment: "内部订单号"
  },
  out_trade_no: {
    type: DataTypes.STRING(64),
    allowNull: false,
    comment: "商户订单号"
  },
  wx_trade_no: {
    type: DataTypes.STRING(64),
    allowNull: true,
    comment: "可能为空"
  },
  total_fee: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: "订单金额;单位为分"
  },
  cash_fee: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: "实付金额;单位为分"
  },
  status: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: "订单状态 0 待拉起支付 1已拉起待支付 2 支付成功 3 支付失败 4支付超时"
  },
  trade_param: {
    type: DataTypes.STRING(512),
    allowNull: true,
    comment: "支付下单参数，用于小程序支付\/H5支付"
  },
  callback_url: {
    type: DataTypes.STRING(255),
    allowNull: true,
    comment: "订单回调地址"
  },
  user_ip: {
    type: DataTypes.STRING(32),
    allowNull: true,
    comment: "用户ip"
  },
  user_open_id: {
    type: DataTypes.STRING(64),
    allowNull: true,
    comment: "用户open_id"
  },
  pay_user_ip: {
    type: DataTypes.STRING(64),
    allowNull: true,
    comment: "支付用户ip"
  },
  create_time: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: "创建时间"
  },
  launch_pay_time: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: "发起支付时间"
  },
  pay_success_time: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: "支付成功时间"
  }
}, {
  sequelize,
  tableName: 'my_pay_order',
  timestamps: false,
  indexes: [
    {
      name: "PRIMARY",
      unique: true,
      using: "BTREE",
      fields: [
        { name: "id" },
      ]
    },
  ]
})

// 数据库初始化方法
async function init() {
  await Counter.sync({ alter: true });
  await Order.sync({ alter: true });
}

// 导出初始化方法和模型
module.exports = {
  init,
  Counter,
  Order
};
